﻿// /////////////////////////////////// 
//  
//  
//      WiseLink CCF2.0 
//     (c)Copyright 2001-2010 WiseLink Xiaojun (David) Chen 
//        Authored and Owned Xiaojun (David) Chen 
//        All Right Reserved
//  
// /////////////////////////////////// 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;

namespace WiseLink.Infrastructure.Common.EntityFramework
{
    public static class EntityHelp
    {
        public static ObjectContext GetContext(this IEntityWithRelationships entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            var relationshipManager = entity.RelationshipManager;

            var relatedEnd = relationshipManager.GetAllRelatedEnds()
                                                .FirstOrDefault();

            if (relatedEnd == null)
                throw new Exception("No relationships found");

            var query = relatedEnd.CreateSourceQuery() as ObjectQuery;

            if (query == null)
                throw new Exception("The Entity is Detached");

            return query.Context;
        }
    }
}
